const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const pool = require('../config/db');
const { logOperation } = require('./logs');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  USER_EXISTS: 1002,
  LOGIN_ERROR: 1004,
  NOT_FOUND: 1005,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

/**
 * 获取用户列表
 * GET /api/users
 * 支持分页和多条件筛选
 */
router.get('/listUsers', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 10, // 默认每页显示10条数据,可自定义ageSize = 10, 
      username, 
      email, 
      roleId = req.query['role_id'], 
      status 
    } = req.query;

    let conditions = [];
    let params = [];

    if (username) {
      conditions.push('u.username LIKE ?');
      params.push(`%${username}%`);
    }
    if (email) {
      conditions.push('u.email LIKE ?');
      params.push(`%${email}%`);
    }
    if (roleId) {
      conditions.push('u.role_id = ?');
      params.push(roleId);
    }
    if (status) {
      conditions.push('u.status = ?');
      params.push(status);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const offset = (parseInt(page) - 1) * parseInt(pageSize);

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM users u ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // 获取用户列表
    const [users] = await pool.execute(
      `SELECT 
        u.id, 
        u.username, 
        u.real_name, 
        u.email, 
        u.role_id, 
        r.name as role_name,
        u.status, 
        u.created_at,
        u.updated_at
      FROM users u
      LEFT JOIN roles r ON u.role_id = r.id
      ${whereClause}
      ORDER BY u.created_at DESC
      LIMIT ?, ?`,
      [...params, offset, parseInt(pageSize)]
    );

    res.json({
      code: 0,
      message: '获取用户列表成功',
      data: {
        total,
        list: users,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      errorDetails: error.message
    });
  }
});

/**
 * 添加用户
 * POST /api/users/add
 */
router.post('/add', async (req, res) => {
  try {
    const {
      username, 
      password, 
      email, 
      realName, 
      roleId = 2, // 默认普通用户角色
      status = 1, // 默认启用状态
    } = req.body;
    
    console.log('用户信息:', {
      username,
      password,
      email,
      realName,
      roleId,
      status
    });

    // 检查必填参数
    if (!username || !password || !email || !realName) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '用户名、密码、邮箱和真实姓名不能为空'
      });
    }

    // 检查用户名和邮箱是否已存在
    const [existingUsers] = await pool.execute(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUsers.length > 0) {
      return res.json({
        code: CODE.USER_EXISTS,
        message: '用户名或邮箱已存在'
      });
    }

    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 插入用户
    const [result] = await pool.execute(
      `INSERT INTO users 
       (username, password, email, real_name, role_id, status, created_at) 
       VALUES (?, ?, ?, ?, ?, ?, NOW())`,
      [
        username, 
        hashedPassword, 
        email, 
        realName, 
        roleId, 
        status
      ]
    );

    // 记录操作日志
    await logOperation(
      // null, 
      // 'user_create', 
      // '用户管理', 
      // `创建用户：${username}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: result.insertId,
        type: 'user_create',
        module: '用户管理',
        details: `创建用户：${username}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '用户创建成功',
      data: { 
        id: result.insertId,
        username,
        email
      }
    });
  } catch (error) {
    console.error('创建用户错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取用户详情
 * GET /api/users/:id
 */
router.get('/details/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 获取用户基本信息
    const [users] = await pool.execute(
      `SELECT id, username, real_name, email, role_id, status, created_at,updated_at
       FROM users
       WHERE id = ?`,
      [id]
    );

    if (users.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在'
      });
    }

    const user = users[0];

    // 获取用户负责的项目
    const [projects] = await pool.execute(
      `SELECT id, name, status, progress
       FROM projects
       WHERE leader_id = ?
       ORDER BY id DESC
       LIMIT 5`,
      [id]
    );

    // 获取用户负责的模块
    const [modules] = await pool.execute(
      `SELECT m.id, m.name, m.status, m.progress,
        p.name as project_name
       FROM modules m
       LEFT JOIN projects p ON m.project_id = p.id
       WHERE m.leader_id = ?
       ORDER BY m.start_date DESC
       LIMIT 5`,
      [id]
    );

    // 获取用户待处理的Bug
    const [bugs] = await pool.execute(
      `SELECT b.id, b.title, b.status, b.severity,
        p.name as project_name,
        m.name as module_name
       FROM bugs b
       LEFT JOIN projects p ON b.project_id = p.id
       LEFT JOIN modules m ON b.module_id = m.id
       WHERE b.assignee_id = ? AND b.status != '已解决'
       ORDER BY b.severity DESC, b.create_time DESC
       LIMIT 5`,
      [id]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取用户详情成功',
      data: {
        ...user,
        projects,
        modules,
        bugs
      }
    });
  } catch (error) {
    console.error('获取用户详情错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 更新用户信息
 * PUT /api/users/update/:id
 */
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;//用户id
    const {
      username,
      email,
      realName,
      roleId,
      status
    } = req.body;

    console.log('更新用户信息:', { id, email,username, realName, roleId, status });

    // 检查用户是否存在
    const [existingUsers] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [id]
    );

    if (existingUsers.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在'
      });
    }

    const existingUser = existingUsers[0];

    // 构建更新字段
    const updateFields = [];
    const updateParams = [];

    if (username) {
      // 检查用户名是否已被其他用户使用
      const [usernameCheck] = await pool.execute(
        'SELECT * FROM users WHERE username = ? AND id != ?',
        [username, id]
      );

      if (usernameCheck.length > 0) {
        return res.json({
          code: CODE.PARAM_ERROR,
          message: '用户名已被其他用户使用'
        });
      }
      updateFields.push('username = ?');
      updateParams.push(username);
    } 

    if (email) {
      // 检查邮箱是否已被其他用户使用
      const [emailCheck] = await pool.execute(
        'SELECT * FROM users WHERE email = ? AND id != ?',
        [email, id]
      );

      if (emailCheck.length > 0) {
        return res.json({
          code: CODE.PARAM_ERROR,
          message: '邮箱已被其他用户使用'
        });
      }
      updateFields.push('email = ?');
      updateParams.push(email);
    }

    if (realName) {
      updateFields.push('real_name = ?');
      updateParams.push(realName);
    }

    if (roleId) {
      // 只有管理员可以修改角色
      if (req.user && req.user.roleId !== 1) {
        return res.json({
          code: CODE.NO_PERMISSION,
          message: '没有权限修改用户角色'
        });
      }
      updateFields.push('role_id = ?');
      updateParams.push(roleId);
    }

    if (status !== undefined) {
      // 只有管理员可以修改状态
      if (req.user && req.user.roleId !== 1) {
        return res.json({
          code: CODE.NO_PERMISSION,
          message: '没有权限修改用户状态'
        });
      }
      updateFields.push('status = ?');
      updateParams.push(status);
    }

    // 处理密码更新
    if (req.body.password) {
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(req.body.password, salt);
      updateFields.push('password = ?');
      updateParams.push(hashedPassword);
    }

    // 添加更新时间
    updateFields.push('updated_at = NOW()');
    updateParams.push(id);

    // 执行更新
    const [result] = await pool.execute(
      `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`,
      updateParams
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null, 
      // 'user_update', 
      // '用户管理', 
      // `更新用户 ${id} 信息`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'user_update',
        module: '用户管理',
        details: `更新用户 ${id} 信息`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    // 获取更新后的用户信息
    const [updatedUsers] = await pool.execute(
      `SELECT id, username, real_name, email, role_id, status, created_at
       FROM users
       WHERE id = ?`,
      [id]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '用户信息更新成功',
      data: updatedUsers[0]
    });
  } catch (error) {
    console.error('更新用户错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 删除用户
 * DELETE /api/users/delete/:id
 */
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 检查用户是否存在
    const [existingUsers] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [id]
    );

    if (existingUsers.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在'
      });
    }

    // 检查用户是否有关联数据（可选）
    const [projectCheck] = await pool.execute(
      'SELECT COUNT(*) as count FROM projects WHERE leader_id = ?',
      [id]
    );

    const [taskCheck] = await pool.execute(
      'SELECT COUNT(*) as count FROM tasks WHERE assignee_id = ?',
      [id]
    );

    if (projectCheck[0].count > 0 || taskCheck[0].count > 0) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '无法删除有关联数据的用户'
      });
    }

    // 执行删除
    await pool.execute(
      'DELETE FROM users WHERE id = ?',
      [id]
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null, 
      // 'user_delete', 
      // '用户管理', 
      // `删除用户 ${id}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'user_delete',
        module: '用户管理',
        details: `删除用户 ${id}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '用户删除成功'
    });
  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 重置用户密码
 * POST /api/users/:id/reset-password
 */
router.post('/:id/reset-password', async (req, res) => {
  try {
    const { id } = req.params;
    const { newPassword } = req.body;

    // 检查用户是否存在
    const [user] = await pool.execute(
      'SELECT username FROM users WHERE id = ?',
      [id]
    );
    if (user.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在'
      });
    }

    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);

    // 更新密码
    await pool.execute(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, id]
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null, 
      // 'update', 
      // '用户管理', 
      // `重置用户 ${user[0].username} 密码`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'update',
        module: '用户管理',
        details: `重置用户 ${user[0].username} 密码`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '重置密码成功'
    });
  } catch (error) {
    console.error('重置密码错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取用户统计信息
 * GET /api/users/statistics/overview
 */
router.get('/statistics/overview', async (req, res) => {
  try {
    // 获取用户角色统计
    const [roleStats] = await pool.execute(
      `SELECT role_id, COUNT(*) as count
       FROM users
       GROUP BY role_id`
    );

    // 获取部门统计
    const [deptStats] = await pool.execute(
      `SELECT department, COUNT(*) as count
       FROM users
       GROUP BY department`
    );

    // 获取状态统计
    const [statusStats] = await pool.execute(
      `SELECT status, COUNT(*) as count
       FROM users
       GROUP BY status`
    );

    // 获取最活跃用户（基于项目和模块数量）
    const [activeUsers] = await pool.execute(
      `SELECT u.id, u.username, u.real_name,
        COUNT(DISTINCT p.id) as project_count,
        COUNT(DISTINCT m.id) as module_count,
        COUNT(DISTINCT b.id) as bug_count
       FROM users u
       LEFT JOIN projects p ON u.id = p.leader_id
       LEFT JOIN modules m ON u.id = m.leader_id
       LEFT JOIN bugs b ON u.id = b.assignee_id AND b.status != '已解决'
       GROUP BY u.id
       ORDER BY (COUNT(DISTINCT p.id) + COUNT(DISTINCT m.id)) DESC
       LIMIT 5`
    );

    // 获取最近登录的用户
    const [recentLogins] = await pool.execute(
      `SELECT id, username, real_name, last_login_time
       FROM users
       WHERE last_login_time IS NOT NULL
       ORDER BY last_login_time DESC
       LIMIT 5`
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取用户统计信息成功',
      data: {
        roleStats,
        deptStats,
        statusStats,
        activeUsers,
        recentLogins
      }
    });
  } catch (error) {
    console.error('获取用户统计信息错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 用户注册
 * POST /api/users/register
 */
router.post('/register', async (req, res) => {
  try {
    const { username, password, email, realName, roleId } = req.body;

    // 检查用户名是否存在
    const [existingUsers] = await pool.execute(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUsers.length > 0) {
      return res.json({
        code: CODE.USER_EXISTS,
        message: '用户名或邮箱已存在'
      });
    }

    // 检查角色是否存在
    const [roles] = await pool.execute(
      'SELECT id FROM roles WHERE id = ?',
      [roleId]
    );

    if (roles.length === 0) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '无效的角色ID'
      });
    }

    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建用户
    const [result] = await pool.execute(
      `INSERT INTO users (username, email, password, real_name, role_id, status)
       VALUES (?, ?, ?, ?, ?, 1)`,
      [username, email, hashedPassword, realName, roleId]
    );

    console.log('注册用户:', {
      id: result.insertId,
      username,
      email,
      realName,
      roleId,
      status: 1
    });

    // 记录操作日志
    await logOperation(
      // result.insertId, 
      // 'user_register', 
      // '用户管理', 
      // `注册用户：${username}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: result.insertId,
        type: 'user_register',
        module: '用户管理',
        details: `注册用户：${username}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '注册成功',
      data: {
        id: result.insertId,
        username,
        email,
        realName,
        roleId,
        status: 1
      }
    });
  } catch (error) {
    console.error('用户注册错误:', error);
    res.json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 用户登录
 * POST /api/users/login
 */
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // 查询用户
    const [users] = await pool.execute(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );

    if (users.length === 0) {
      return res.json({
        code: CODE.LOGIN_ERROR,
        message: '用户不存在'
      });
    }

    const user = users[0];

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.json({
        code: CODE.LOGIN_ERROR,
        message: '密码错误'
      });
    }

    console.log('登录用户:', {
      id: user.id,
      username: user.username,
      roleId: user.role_id
    });
    
    // 生成 JWT Token
    const token = jwt.sign(
      { 
        id: user.id, 
        username: user.username, 
        roleId: user.role_id 
      }, 
      process.env.JWT_SECRET, 
      { expiresIn: '24h' }
    );

    // 记录登录日志
    await logOperation(
      // user.id,
      // 'login',
      // '用户管理',
      // `用户 ${username} 登录成功`,
      // req.ip,
      // req.headers['user-agent']
      {
        userId: user.id,
        type: 'login',
        module: '用户管理',
        details: `用户 ${username} 登录成功`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '登录成功',
      data: {
        token,
        userId: user.id,
        username: user.username,
        roleId: user.role_id
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 获取角色列表
 * GET /api/users/roles
 */
router.get('/roles', async (req, res) => {
  try {
    const [roles] = await pool.execute(
      'SELECT id, name, description FROM roles ORDER BY id'
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取角色列表成功',
      data: roles
    });
  } catch (error) {
    console.error('获取角色列表错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

/**
 * 修改用户状态
 * PUT /api/users/change-status
 */
router.post('/change-status', async (req, res) => {
  try {
    const { uid,status } = req.body;

    if (status === undefined) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '状态不能为空'
      });
    }

    const [result] = await pool.execute(
      'UPDATE users SET status = ?, updated_at = NOW() WHERE id = ?',
      [status, uid]
    );

    if (result.affectedRows === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在'
      });
    }

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null, 
      // 'update', 
      // '用户管理', 
      // `更新用户 ${uid} 状态为 ${status}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'update',
        module: '用户管理',
        details: `更新用户 ${uid} 状态为 ${status}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '用户状态更新成功'
    });
  } catch (error) {
    console.error('更新用户状态错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 退出登录
router.get('/logout', (req, res) => {
  // 清除 JWT Token
  res.clearCookie('token'); 

  // 清除本地存储的用户信息-这是前端要做的
  // localStorage.removeItem('token');
  // localStorage.removeItem('userInfo');
  // localStorage.removeItem('userRole');
  // localStorage.removeItem('userRoleId');

  // 记录操作日志
  logOperation(
    // req.user ? req.user.userId : null, 
    // 'logout', 
    // '用户管理', 
    // '用户退出登录', 
    // req.ip || '', 
    // req.headers['user-agent'] || ''
    {
      userId: req.user ? req.user.userId : null,
      type: 'logout',
      module: '用户管理',
      details: '用户退出登录',
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    }
  );

  // 返回成功响应
  res.json({
    code: CODE.SUCCESS,
    message: '退出登录成功'
  });
});

// 修改密码
router.put('/password', async (req, res) => {
  try {
    const { userId } = req.user;
    const { oldPassword, newPassword } = req.body;

    // 查询用户
    const [users] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '用户不存在'
      });
    }    

    // 验证旧密码
    const user = users[0];
    const isMatch = await bcrypt.compare(oldPassword, user.password);
    if (!isMatch) {
      return res.json({
        code: CODE.PASSWORD_ERROR,
        message: '旧密码错误'
      });
    }        

    // 更新密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);
    await pool.execute(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, userId]
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null, 
      // 'update', 
      // '用户管理', 
      // `用户 ${user.username} 修改密码`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'update',
        module: '用户管理',
        details: `用户 ${user.username} 修改密码`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '密码修改成功'
    });
  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
}); 

module.exports = router;
